package com.flame.core.utils.cipher;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.bouncycastle.util.encoders.Hex;

/**
 * Sm4Cipher
 *
 * @author wuxintong
 * @since 2023/1/28
 */
public class Sm4Cipher implements FlameCipher {

    private static final String KEY = "FF*%!KC$EW#xm777";

    public Map<String, String> generateKey() {
        Map<String, String> map = new HashMap<>();
        // 转换成前端 SM4 秘钥 46462a25214b4324455723786d373737
        map.put("frontSecretKey", Hex.toHexString(KEY.getBytes(StandardCharsets.UTF_8)));
        return map;
    }

    @Override
    public String encrypt(String data) throws Exception {
        return encrypt(data, KEY);
    }

    @Override
    public String decrypt(String data) throws Exception {
        return decrypt(data, KEY);
    }

    @Override
    public String encrypt(String data, String key) throws Exception {
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "SM4");
        Cipher cipher = Cipher.getInstance("SM4/CBC/PKCS5Padding");
        IvParameterSpec ivParameterSpec = new IvParameterSpec(key.getBytes(StandardCharsets.UTF_8));
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
        byte[] res = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
        return new String(Hex.encode(res));
    }

    @Override
    public String decrypt(String data, String key) throws Exception {
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "SM4");
        Cipher cipher = Cipher.getInstance("SM4/CBC/PKCS5Padding");
        IvParameterSpec ivParameterSpec = new IvParameterSpec(key.getBytes(StandardCharsets.UTF_8));
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
        byte[] bytes = cipher.doFinal(Hex.decode(data.getBytes(StandardCharsets.UTF_8)));
        return new String(bytes, StandardCharsets.UTF_8);
    }
}
